/**********************************************************************
 * Copyright (C) 2019  Unisound
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 **********************************************************************
 *
 * Description : base64.h
 * Author      : ivm@unisound.com
 * Date        : 2019.10.30
 *
 **********************************************************************/
#include "base64.h"

char *base64_encode(char *str) {
  int len;
  int str_len;
  unsigned char *res = NULL;
  int i, j;
  const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  if(NULL == str) {
    return NULL;
  }
  str_len = uni_strlen(str);
  if(str_len % 3 == 0) {
    len = str_len / 3 * 4;
  } else {
    len = (str_len / 3 + 1) * 4;
  }
  res = uni_malloc(sizeof(unsigned char) * len + 1);
  if (NULL == res) {
    return NULL;
  }

  res[len] = '\0';
  for(i = 0, j = 0; i < len - 2; j += 3, i += 4) {
    res[i] = base64_table[str[j] >> 2];
    res[i + 1] = base64_table[(str[j] & 0x3) << 4 | (str[j + 1] >> 4)];
    res[i + 2] = base64_table[(str[j + 1] & 0xf) << 2 | (str[j + 2] >> 6)];
    res[i + 3] = base64_table[str[j + 2] & 0x3f];
  }

  switch(str_len % 3) {
    case 1:
      res[i - 2] = '=';
      res[i - 1] = '=';
      break;
    case 2:
      res[i - 1] = '=';
      break;
  }

  return (char *)res;
}
